package com.mvc.interceptor;

import com.mvc.DispatchServlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JsonResponseInterceptor implements HandlerInterceptor{
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object result) throws Exception {
		
		// result 是目标方法的返回结果
		// 改成json 格式响应
		response.setContentType("application/json;charset=utf-8");
		String json = null;
		if (result instanceof String) {
			json = (String) result;
		} else {
			json = DispatchServlet.getObjectMapper().writeValueAsString(result);        // objectMapper 从哪里来？
		}
		
		// 根据json 响应状态，设置http响应
		response.getWriter().write(json);
	}
}
